import { dataType } from 'element-plus/es/components/table-v2/src/common';
import {
  getUser, allRole, delRole, updateRole,
} from '@/api/role';
import addForTree from '@/components/addForTee.vue';

export default {
  name: 'rolePage',
  components: {
    addForTree,
  },
  data() {
    return {
      tableData: [],
      total: 0,
      curuid: null,
      showRoleDrawer: false,
      roleData: [
        {
          name: 'root',
          id: 0,
          children: [],
        },
      ],
    };
  },
  created() {
    this.getList();
    this.getAllRole();
  },
  methods: {
    async getAllNodes() {
      const nodes = this.$refs.roleTree.getCheckedNodes();
      console.log('nodes', nodes);
      const res = await updateRole(this.curuid, JSON.stringify(nodes));
      console.log('权限更新的结果是', res);
      const { statusText } = res;
      if (statusText === 'OK') {
        this.$message.success('设置成功');
        this.showRoleDrawer = false;
        this.getList();
      }
    },
    async delRole(id) {
      const res = await delRole(id);
      console.log(res);
      const { statusText } = res;
      if (statusText === 'OK') {
        // 如果是配置api 可以直接在实例上访问$message
        this.$message.success('删除成功');
        this.getAllRole();
      }
    },
    async getAllRole() {
      const res = await allRole();
      const { statusText, data } = res;
      // eslint-disable-next-line
      console.log('data', data.data);

      // 扁平数组  进行 树状处理
      // eslint-disable-next-line
      for (const item of data.data) {
        const { pid } = item; // 父级别id
        const parent = data.data.find((it) => it.id === pid);
        if (parent) {
          if (!parent.children) parent.children = [];
          parent.children.push(item);
        }
      }

      this.roleData = [
        {
          name: 'root',
          id: 0,
          children: data.data.filter((item) => item.pid === 0),
        },
      ];
    },
    async getList() {
      const res = await getUser();

      const { statusText, data } = res;

      if (statusText === 'OK') {
        this.tableData = data.data;
        this.total = data.total;
      }
    },
    openRoleDialog({ id, roles = '[]' }) {
      // console.log('id', id);
      this.curuid = id;
      this.showRoleDrawer = true;
      // eslint-disable-next-line
      if (!roles) roles = '[]';
      // 我们在数据库当中存储的roles是一个数组的字符串化的内容
      const checkIds = JSON.parse(roles);
      const ids = checkIds.map((item) => item.id);

      this.$nextTick(() => {
        console.log('roleTree', this.$refs.roleTree);
        // 尝试一下 setCheckedKeys
        this.$refs.roleTree.setCheckedKeys(ids);
      });
    },
  },
};
